<template>
    <div>
        <!--  面包屑  -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>
        <!--  卡片  -->
        <el-card>
            <!--      提示框区      -->
            <el-alert
                    center
                    show-icon
                    :closable="false"
                    title="添加商品信息"
                    type="info">
            </el-alert>
            <div style="height: 20px"></div>
            <!--      步骤条      -->
            <el-steps :active="activeIndex - 0"
                      finish-status="success"
                      align-center>
                <el-step title="基本信息"></el-step>
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>
            <div style="height: 15px;"></div>
            <!--      表单区域      -->
            <el-form :model="addFromGoogs"
                     :rules="addFromGoogsRules"
                     ref="updateFromRef"
                     label-position="top"
                     label-width="100px">
                <!--     标签页区域       -->
                <el-tabs :tab-position="tabPosition"
                         :before-leave="btnChangeTabs"
                         @tab-click="tabClicked"
                         v-model="activeIndex">
                    <el-tab-pane label="基本信息" name="0">
                        <el-form-item label="商品名称"
                                      prop="goods_name">
                            <el-input v-model="addFromGoogs.goods_name"></el-input>
                        </el-form-item>
                        <el-form-item label="商品价格"
                                      prop="goods_price">
                            <el-input
                                    type="number"
                                    v-model="addFromGoogs.goods_price"></el-input>
                        </el-form-item>
                        <el-form-item label="商品数量"
                                      prop="goods_number">
                            <el-input
                                    type="number"
                                    v-model="addFromGoogs.goods_number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品重量"
                                      prop="goods_weight">
                            <el-input
                                    type="number"
                                    v-model="addFromGoogs.goods_weight"></el-input>
                        </el-form-item>
                        <el-form-item
                                prop="goods_cat"
                                label="商品分类">
                            <el-cascader
                                    expand-trigger="hover"
                                    v-model="addFromGoogs.goods_cat"
                                    :props="cascaderProps"
                                    change-on-select
                                    @change="handleChange"
                                    clearable
                                    :options="setparamsList">
                            </el-cascader>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品参数" name="1">
                        <el-form-item :label="item.attr_name"
                                      :key="item.attr_id"
                                      v-for="item in manyTableData">
                            <el-checkbox-group v-model="item.attr_vals">
                                <el-checkbox :label="j"
                                             :key="i"
                                             border
                                             v-for="(j,i) in item.attr_vals">
                                </el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品属性" name="2">
                        <el-form-item :label="item.attr_name"
                                      :key="item.attr_id"
                                      v-for="item in onlyTableData">
                            <el-input v-model="item.attr_vals"></el-input>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品图片" name="3">
                        <el-upload
                                :headers="headerObj"
                                :on-success="handleSuccess"
                                class="upload-demo"
                                multiple
                                :limit="10"
                                action="http://127.0.0.1:8888/api/private/v1/upload"
                                :on-preview="handlePreview"
                                :on-remove="handleRemove"
                                list-type="picture">
                            <el-button size="small"
                                       type="primary">点击上传
                            </el-button>
                        </el-upload>
                    </el-tab-pane>
                    <el-tab-pane label="商品内容" name="4">
                        <quill-editor v-model="addFromGoogs.goods_introduce"
                                      ref="myQuillEditor"
                                      :options="editorOption"
                                      @blur="onEditorBlur($event)"
                                      @focus="onEditorFocus($event)"
                                      @ready="onEditorReady($event)">
                        </quill-editor>
                        <div style="height: 10px"></div>
                        <el-button
                                @click="addGoogsFrom"
                                type="primary">添加商品
                        </el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </el-card>
        <!--    图片预览对话框    -->
        <el-dialog
                title="图片预览"
                :visible.sync="lookImgVisible"
                width="50%">
            <!--   主体区域   -->
            <img class="viewImg" :src="privewPic">
        </el-dialog>
    </div>
</template>

<script>
  import _ from 'lodash';
  export default {
    name: "Add",
    data() {
      return {
        // 状态变量
        activeIndex: '0',
        // 标签页
        tabPosition: 'left',
        // 分类数据
        setparamsList: [],
        // 级联配置
        cascaderProps: {
          value: 'cat_id',
          label: 'cat_name',
          children: 'children'
        },
        // 动态参数列表
        manyTableData: [],
        onlyTableData: [],
        // 图片上传参数
        headerObj: {
          Authorization: window.sessionStorage.getItem('token')
        },
        // 预览
        privewPic: '',
        lookImgVisible: false,
        editorOption: {},
        // 表单数据对象
        addFromGoogs: {
          goods_name: '',
          goods_price: 0,
          goods_number: 0,
          goods_weight: 0,
          goods_cat: [],
          pics: [],
          goods_introduce: '',
          attrs: []
        },
        // 验证规则
        addFromGoogsRules: {
          goods_name: [
            {
              required: true, message: '请输入商品名', trigger: 'blur'
            }
          ],
          goods_price: [
            {
              required: true, message: '请输入价格', trigger: 'blur'
            }
          ],
          goods_number: [
            {
              required: true, message: '请输入数量', trigger: 'blur'
            }
          ],
          goods_weight: [
            {
              required: true, message: '请输入重量', trigger: 'blur'
            }
          ],
          goods_cat: [
            {
              required: true, message: '请选择商品分类', trigger: 'blur'
            }
          ]
        }
      }
    },
    mounted() {
      this.getCategories()
    },
    methods: {
      // 分类请求
      getCategories() {
        this.$http.get('categories').then(res => {
          if (res.data.meta.status !== 200) {
            return this.$message.error(res.data.meta.msg)
          }
          this.setparamsList = res.data.data
        })
      },
      // 监听级联选择框
      handleChange() {
        console.log(this.addFromGoogs.goods_cat)
        if (this.addFromGoogs.goods_cat.length !== 3) {
          this.addFromGoogs.goods_cat = []
        }
      },
      // 监听标签页切换校验
      btnChangeTabs(activeName, oldActiveName) {
        if (oldActiveName === '0' && this.addFromGoogs.goods_cat.length !== 3) {
          this.$message.error('请先选择商品分类')
          return false
        }
      },
      // 选中标签事件
      tabClicked() {
        if (this.activeIndex === '1') {
          // 动态参数面板
          this.$http.get(`categories/${this.cateId}/attributes`, {
            params: {
              sel: 'many'
            }
          }).then(res => {
            if (res.data.meta.status !== 200) {
              return this.$message.error(res.data.meta.msg)
            }
            // 数据转换
            res.data.data.forEach(item => {
              item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
            })
            this.manyTableData = res.data.data
          })
        } else if (this.activeIndex === '2') {
          // 静态属性面板
          this.$http.get(`categories/${this.cateId}/attributes`, {
            params: {
              sel: 'only'
            }
          }).then(res => {
            if (res.data.meta.status !== 200) {
              return this.$message.error(res.data.meta.msg)
            }
            this.onlyTableData = res.data.data
          })
        }
      },
      // 图片上传
      // 预览
      handlePreview(file) {
        console.log(file.url)
        this.privewPic = file.response.data.url
        this.lookImgVisible = true
      },
      // 移除
      handleRemove(file) {
        // 获取删除的图片路径
        const filePath = file.response.data.tmp_path
        // 获取图片索引
        const i = this.addFromGoogs.pics.findIndex(x => x.pic === filePath)
        // 根据索引删除
        this.addFromGoogs.pics.splice(i, 1)
        console.log(this.addFromGoogs.pics)
      },
      // 返回图片url
      handleSuccess(response) {
        // 封装对象
        let imgObj = {
          pic: response.data.tmp_path
        }
        // 添加到数组中
        this.addFromGoogs.pics.push(imgObj)
      },
      // 富文本编辑器
      onEditorBlur(quill) {
      },
      onEditorFocus(quill) {
      },
      onEditorReady(quill) {
      },
      // 添加商品
      addGoogsFrom() {
        this.$refs.updateFromRef.validate(valid => {
          if (!valid) {
            return this.$message.error('请填写必要的数据')
          }
          // 数据处理
          // 深拷贝
          const from = _.cloneDeep(this.addFromGoogs)
          from.goods_cat = from.goods_cat.join(',')
          // 动态参数
          this.manyTableData.forEach(item => {
            const newInfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals
            }
            this.addFromGoogs.attrs.push(newInfo)
          })
          // 静态属性
          this.onlyTableData.forEach(item => {
            const newInfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals
            }
            this.addFromGoogs.attrs.push(newInfo)
          })
          from.attrs = this.addFromGoogs.attrs
          //请求
          this.$http.post('goods', from).then(res => {
            if (res.data.meta.status !== 201) {
              return this.$message.error(res.data.meta.msg)
            }
            this.$message.success(res.data.meta.msg)
            this.$router.push('/goods')
          })
        })
      }
    },
    computed: {
      // 计算属性
      // 获取动态id
      cateId() {
        if (this.addFromGoogs.goods_cat.length === 3) {
          return this.addFromGoogs.goods_cat[2]
        }
        return null
      },
    }
  }
</script>

<style lang="less" scoped>
    .el-checkbox {
        margin: 5px 10px 0 5px !important;
    }

    .viewImg {
        width: 100%;
    }

</style>
